package com.uinnova.product.eam.web.eam.mvc;

import com.alibaba.fastjson.JSONObject;
import com.binary.core.exception.MessageException;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.util.ControllerUtils;
import com.binary.framework.web.RemoteResult;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.model.EamArtifactCdt;
import com.uinnova.product.eam.model.EamArtifactElementVo;
import com.uinnova.product.eam.model.EamArtifactVo;
import com.uinnova.product.eam.model.dto.ArtifactElementDto;
import com.uinnova.product.eam.model.dto.ElementConditionDto;
import com.uinnova.product.eam.model.dto.ElementDto;
import com.uinnova.product.eam.model.vo.CiClassRltVo;
import com.uinnova.product.eam.model.vo.DefaultFileVo;
import com.uinnova.product.eam.service.IEamArtifactColumnSvc;
import com.uinnova.product.eam.service.IEamArtifactSvc;
import com.uinnova.product.eam.service.utils.PageUtil;
import com.uinnova.product.vmdb.comm.doc.annotation.ModDesc;
import com.uinnova.product.vmdb.comm.doc.annotation.MvcDesc;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uino.web.auth.VerifyAuthUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/eam/artifact")
@MvcDesc(author = "wcl", desc = "制品管理")
public class EamArtifactMvc {
    public static final String SYS_MODULE_SIGN = "制品类型管理新版";
    @Resource
    private IEamArtifactSvc iEamArtifactSvc;
    @Resource
    private IEamArtifactColumnSvc iEamArtifactColumnSvc;
    @Autowired
    private VerifyAuthUtil verifyAuth;

    @PostMapping(value = "/saveOrUpdate")
    @ModDesc(desc = "新建制品信息得添加/修改", pDesc = "制品类型", rDesc = "", rType = RemoteResult.class)
    public RemoteResult saveOrUpdate(@RequestBody EamArtifactCdt cdt) {
        Long id = iEamArtifactSvc.saveOrUpdate(cdt);
        return new RemoteResult(id);
    }

    @GetMapping(value = "/deleteArtifact")
    @ModDesc(desc = "逻辑删除制品类型", pDesc = "制品类型id", rDesc = "", rType = RemoteResult.class)
    public RemoteResult deleteArtifact(@RequestParam Long artifactId) {
        Long id = iEamArtifactSvc.deleteArtifact(artifactId);
        return new RemoteResult(id);
    }

    @GetMapping(value = "/releaseArtifact")
    @ModDesc(desc = "发布/取消发布制品", pDesc = "制品类型id", rDesc = "", rType = RemoteResult.class)
    public RemoteResult releaseArtifact(@RequestParam Long artifactId, @RequestParam Integer releaseState) {
        Long id = iEamArtifactSvc.releaseArtifact(artifactId, releaseState);
        return new RemoteResult(id);
    }

    @GetMapping(value = "/checkBeforeReleaseArtifact")
    @ModDesc(desc = "制品取消发布前校验", pDesc = "制品类型id", rDesc = "", rType = RemoteResult.class)
    public RemoteResult checkBeforeReleaseArtifact(@NotNull @RequestParam Long artifactId) {
        String message = iEamArtifactSvc.checkBeforeReleaseArtifact(artifactId);
        return new RemoteResult(message);
    }

    @RequestMapping(value = "/queryElements")
    @ModDesc(desc = "查询所有制品类型标签", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public void queryElements(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Long> collect = iEamArtifactSvc.queryAllElements();
        ControllerUtils.returnJson(request, response, collect);
    }

    @PostMapping("/queryArtifactList")
    @Deprecated
    @ModDesc(desc = "查询制品列表信息，按制品类型名称（支持模糊查）进行搜索查询", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult queryArtifactList(@RequestBody ElementConditionDto dto) {
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        if(dto.getPostProcessParam()!=null && !BinaryUtils.isEmpty(dto.getPostProcessParam().get("classId"))){
            dto.setPageSize(1000);
        }
        Page<EamArtifactVo> pageVos = iEamArtifactSvc.queryArtifactList(dto);
        if(dto.getPostProcessParam()!=null && !BinaryUtils.isEmpty(dto.getPostProcessParam().get("classId"))){
            List<EamArtifactVo> result = iEamArtifactSvc.queryArtifactByClass(pageVos.getData(), dto.getPostProcessParam());
            PageUtil<EamArtifactVo> pageUtil = new PageUtil<>(pageNum, pageSize, result);
            return new RemoteResult(pageUtil);
        }
        return new RemoteResult(pageVos);
    }

    @RequestMapping("/queryArtifact")
    @ModDesc(desc = "制品基本信息的查询", pDesc = "制品类型id", rDesc = "制品基本信息", rType = RemoteResult.class)
    public void queryArtifact(HttpServletRequest request, HttpServletResponse response, @RequestParam Long artifactId) {
        EamArtifactVo eamArtifact = iEamArtifactSvc.queryArtifact(artifactId);
        ControllerUtils.returnJson(request, response, eamArtifact);
    }

    @PostMapping(value = "/saveOrUpdateColumn")
    @ModDesc(desc = "新增制品-图例分栏信息添加/修改", pDesc = "制品分栏信息", rDesc = "", rType = RemoteResult.class)
    public void saveOrUpdateColumn(HttpServletRequest request, HttpServletResponse response, @RequestBody ArtifactElementDto elements) {
        Integer nums = iEamArtifactColumnSvc.saveOrUpdate(elements);
        ControllerUtils.returnJson(request, response, nums);

    }

    @RequestMapping(value = "/queryAllColumns")
    @ModDesc(desc = "根据制品id查询分栏信息", pDesc = "制品类型id", rDesc = "", rType = RemoteResult.class)
    public void queryAllColumns(HttpServletRequest request, HttpServletResponse response, @RequestBody ElementDto elementDto) {
        List<EamArtifactElementVo> columns = iEamArtifactColumnSvc.queryAllColumns(elementDto);
        ControllerUtils.returnJson(request, response, columns);
    }

    @RequestMapping(value = "/queryByVisualModel")
    @ModDesc(desc = "元模型中查询对象之间的关系", pDesc = "制品类型id", rDesc = "", rType = RemoteResult.class)
    public void queryRelationFromObjects(HttpServletRequest request, HttpServletResponse response, @RequestBody List<Long> ciClassIds) {
        List<CiClassRltVo> relations = iEamArtifactColumnSvc.queryRelationFromObjects(ciClassIds);
        ControllerUtils.returnJson(request, response, relations);
    }

    @RequestMapping("/defaultImage")
    @ModDesc(desc = "查询制品默认图接口", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public void defaultImage(HttpServletRequest request, HttpServletResponse response) {
        List<DefaultFileVo> vo = iEamArtifactSvc.defaultImage();
        ControllerUtils.returnJson(request, response, vo);
    }

    @GetMapping("/images")
    @ModDesc(desc = "查询制品示例图", pDesc = "", rDesc = "", rType = DefaultFileVo.class)
    public RemoteResult getImages() {
        List<DefaultFileVo> vo = iEamArtifactSvc.getImages();
        return new RemoteResult(vo);
    }

    @ResponseBody
    @RequestMapping("/queryArtifactTemplateById")
    @ModDesc(desc = "根据制品id查询模板信息", pDesc = "", rDesc = "制品id", rType = RemoteResult.class)
    public RemoteResult queryArtifactByType(@RequestParam Long artifactId, @RequestBody String body) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        BinaryUtils.checkEmpty(jsonObject.getLong("pageNum"), "pageNum");
        BinaryUtils.checkEmpty(jsonObject.getLong("pageSize"), "pageSize");
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String like = jsonObject.getString("like");
        Page<ESDiagram> diagramPage = iEamArtifactColumnSvc.queryTemplateByArtifactId(artifactId, pageNum, pageSize, like);
        return new RemoteResult(diagramPage);
    }

    @PostMapping(value = "/refreshData")
    @ModDesc(desc = "刷制品子表存量数据（type为null）", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult refreshData(HttpServletRequest request, HttpServletResponse response) {
        Integer result = iEamArtifactColumnSvc.refreshData();
        return new RemoteResult(result);
    }

    @GetMapping("/getArchSystemList")
    public RemoteResult getArchSystemList(Long artifactId) {
        List<Map<String, Object>> list = iEamArtifactColumnSvc.getArchSystemList(artifactId);
        return new RemoteResult(list);
    }

    @GetMapping("/copyArtifact")
    @ModDesc(desc = "复制制品", pDesc = "制品id", rDesc = "", rType = RemoteResult.class)
    public void copyArtifact(HttpServletRequest request, HttpServletResponse response, @RequestParam @NotNull Long artifactId) {
        Long copyArtifactId = iEamArtifactSvc.copyArtifact(artifactId);
        ControllerUtils.returnJson(request, response, copyArtifactId);
    }

    @GetMapping("/exportArtifact")
    @ModDesc(desc = "导出单个制品", pDesc = "制品id", rDesc = "", rType = RemoteResult.class)
    public ResponseEntity<byte[]> exportArtifact(@RequestParam @NotNull Long artifactId) {
        return iEamArtifactSvc.exportArtifact(artifactId);
    }

    @PostMapping("/importArtifact")
    @ModDesc(desc = "导入单个制品", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult importArtifact(@RequestPart("zipFile") @NotNull MultipartFile zipFile) {
        RemoteResult result = null;
        //文件上传前的名称
        String originFileName = zipFile.getOriginalFilename();
        assert originFileName != null;
        File file = new File(originFileName);
        try (OutputStream out = new FileOutputStream(file)) {
            IOUtils.copy(zipFile.getInputStream(),out);
            IOUtils.closeQuietly(out);
            String s = iEamArtifactSvc.importArtifact(file);
            result = new RemoteResult(s);
        } catch (Exception e) {
            throw new MessageException(e.getMessage());
        } finally {
            //删除临时目录
            FileUtils.deleteQuietly(file);
        }
        return result;
    }
    @GetMapping("/crushArtifactColumns")
    @ModDesc(desc = "刷新存量数据-制品分栏中架构元素增加一个classCode字段", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public void crushArtifactColumns(HttpServletRequest request, HttpServletResponse response) {
         String s = iEamArtifactSvc.crushArtifactColumns();
        ControllerUtils.returnJson(request, response, s);
    }

    @GetMapping("/crushArtifactColumnsRelation")
    @ModDesc(desc = "刷新存量数据-制品分栏中架构元素增加一个classCode字段", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public void crushArtifactColumnsRelation(HttpServletRequest request, HttpServletResponse response) {
        String s = iEamArtifactSvc.crushArtifactColumnsRelation();
        ControllerUtils.returnJson(request, response, s);
    }

    @GetMapping("/crushCreator")
    @ModDesc(desc = "刷新存量数据-刷入创建人字段", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public void crushCreator(HttpServletRequest request, HttpServletResponse response) {
        String s = iEamArtifactSvc.crushCreator();
        ControllerUtils.returnJson(request, response, s);
    }

    @RequestMapping(value = "/queryArtifactInfoById")
    public void queryArtifactInfoById(HttpServletRequest request, HttpServletResponse response,@RequestParam Long artifactId) {
        Map<String, Object> artifactInfo = iEamArtifactSvc.queryArtifactInfoById(artifactId);
        ControllerUtils.returnJson(request, response, artifactInfo);
    }

}
